package javase.jmx.monitoring;

import java.lang.management.ManagementFactory;

import javax.management.Attribute;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public class MBeanPrppertyIncremetHelper implements Runnable {
	private String mBeanName;
	private String propertyName;
	private int incrementInterval;
	private MBeanServer mBeanServer;
	
	public MBeanPrppertyIncremetHelper(String mBeanName, String propertyName) {
		this.mBeanName = mBeanName;
		this.propertyName = propertyName;
		this.incrementInterval = 300;
		this.mBeanServer = ManagementFactory.getPlatformMBeanServer();
	}

	@Override
	public void run() {
		try {
			continuouslyIncrement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void continuouslyIncrement() throws Exception {
		ObjectName objectName = new ObjectName(mBeanName);
		while (true) {
			incrementProperty(objectName);
			Thread.sleep(incrementInterval);
		}
	}

	private void incrementProperty(ObjectName objectName) throws Exception {
		int value = (Integer)mBeanServer.getAttribute(objectName, propertyName);
		value++;
		Attribute newValue = new Attribute(propertyName, value);
		mBeanServer.setAttribute(objectName, newValue);
	}

}
